// Copyright (c) 2022 CHANGLEI. All rights reserved.

import 'dart:ui' as ui;

import 'package:aircraft_war/bloc/game_state_cubit.dart';
import 'package:aircraft_war/components/game_pending.dart';
import 'package:aircraft_war/components/game_running.dart';
import 'package:flame/components.dart';
import 'package:flutter/widgets.dart' as widgets;

/// Created by changlei on 2022/5/18.
///
/// 覆盖层
class GameOverlay extends GameStatePositionComponent {
  GamePending? _gamePending;
  GameRunning? _gameRunning;

  @override
  void onGameResize(Vector2 size) {
    super.onGameResize(size);
    final mediaQueryData = widgets.MediaQueryData.fromWindow(ui.window);
    final padding = mediaQueryData.padding;
    this.size = Vector2(size.x - padding.horizontal, size.y - padding.vertical);
    position = Vector2(padding.left, padding.top);

    _gamePending?.layout(this.size);
    _gameRunning?.layout(this.size);
  }

  @override
  Future<void> onLoad() async {
    onNewState(gameRef.stateCubit.state);
  }

  @override
  void onNewState(GameState state) {
    switch (state) {
      case GameState.idle:
      case GameState.pending:
      case GameState.stopped:
        _gameRunning?.removeFromParent();
        _gameRunning = null;
        if (_gamePending == null) {
          final gamePending = GamePending();
          gamePending.layout(size);
          _gamePending = gamePending;
          add(gamePending);
        }
        break;
      case GameState.running:
      case GameState.pausing:
        _gamePending?.removeFromParent();
        _gamePending = null;
        if (_gameRunning == null) {
          final gameRunning = GameRunning();
          gameRunning.layout(size);
          _gameRunning = gameRunning;
          add(gameRunning);
        }
        break;
    }
  }
}
